package com.ruoyi.operator.utils;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Component
public class NeteaseUtil {

    public static  String REQUEST_URL = "https://api.netease.im/nimserver/user/create.action";

    /**
     * 创建网易云信用户
     * @param : accid 用户环信id/token信息
     * @return :
     */
    public static String registNeteaseID(String accid) {

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(REQUEST_URL);

//        String nonce = UUID.randomUUID().toString();
        String appKey = "f1b827da89006ecc5a65c6925682c80c";
        String appSecret = "cb392371d6cb";
        String nonce = "wenzhen";
        String curTime = String.valueOf((new Date()).getTime() / 1000L);
        //参考 计算CheckSum的java代码
        String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);


        // 设置请求的header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("accid", accid));
        nvps.add(new BasicNameValuePair("name", ""));
        String sRetCode = "";
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            HttpResponse response = httpClient.execute(httpPost);
            String json = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject obj = JSONObject.parseObject(json);
            if (obj.getString("code").equals("200")) {
                JSONObject info = obj.getJSONObject("info");
                sRetCode = info.getString("token");
            } else if (obj.getString("code").equals("414")) {
                sRetCode = "414";
            } else {
                sRetCode = "999";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sRetCode;

    }
}
